import pygame
import math

class Projectile(pygame.sprite.Sprite):
    duration = 0
    
    
    def __init__(self, tower, target, duration):
        pygame.sprite.Sprite.__init__(self) 
    
        self.tower = tower
        self.target = target
        self.duration = duration

        self.rect = pygame.Rect((self.tower.rect.left, self.tower.rect.top), (10, 10))

        self.rect.centerx = self.tower.rect.centerx
        self.rect.centery = self.tower.rect.centery

    def update(self):
        self.move()
        self.duration -= 1
        if self.duration <= 0:
            self.kill()
        if self.target.health <= 0:
            self.kill()
        if pygame.sprite.collide_rect(self, self.target):
            self.tower.on_hit(self.target)
            self.kill()
    
    def move(self):
        speed = 20
        
        x = self.rect.centerx - self.target.rect.centerx
        y = self.rect.centery - self.target.rect.centery
        angle = math.atan2(y, x)
        
        self.rect.centerx -= speed*math.cos(angle)
        self.rect.centery -= speed*math.sin(angle)
    
    def draw(self, screen):
        pygame.draw.circle(screen, self.tower.projectile_color, \
                           (self.rect.centerx, self.rect.centery), \
                           5, 0)